/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * votacionPrimaria.java
 *
 * Created on Jul 22, 2012, 5:46:41 PM
 */

package vistas;

import cliente.conexionPP;
import cliente.conexionRE;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Stev
 */
public class votacionPrimaria extends javax.swing.JPanel {
    private String IP_PP;
    private String IP_RE;
            
    private conexionRE conexion = new conexionRE();
    private conexionPP conexionPP = new conexionPP();
    boolean puede_votar= false;
    /** Creates new form votacionPrimaria */
    public votacionPrimaria(String IP_RE, String IP_PP) {
        this.IP_RE= IP_RE;
        this.IP_PP= IP_PP;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jComboBoxPartido = new javax.swing.JComboBox();
        jComboBoxComuna = new javax.swing.JComboBox();
        jComboBox3 = new javax.swing.JComboBox();
        jTextField_RUT = new javax.swing.JTextField();
        jButtonEscogerPyC = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaResultado = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        jComboBoxPartido.addItem("PC");
        jComboBoxPartido.addItem("DC");
        jComboBoxPartido.addItem("UDI");

        jComboBoxComuna.addItem("Ninguna");
        jComboBoxComuna.addItem("Heterogeneidad");
        jComboBoxComuna.addItem("Escalabilidad");
        jComboBoxComuna.addItem("Transparencia");
        jComboBoxComuna.addItem("Concurrencia");
        jComboBoxComuna.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jComboBoxComuna.setEnabled(false);

        jButtonEscogerPyC.setText("Escoger Partido y Comuna");
        jButtonEscogerPyC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEscogerPyCActionPerformed(evt);
            }
        });

        jLabel1.setText("RUT:");

        jLabel2.setText("Partido:");

        jLabel3.setText("Comuna:");

        jLabel4.setText("Candidatos:");

        jTextAreaResultado.setColumns(20);
        jTextAreaResultado.setRows(5);
        jScrollPane1.setViewportView(jTextAreaResultado);

        jButton2.setText("Votar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jComboBox3, 0, 121, Short.MAX_VALUE)
                .add(45, 45, 45)
                .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 94, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(65, 65, 65))
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(20, 20, 20)
                        .add(jSeparator1))
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(30, 30, 30)
                        .add(jScrollPane1))
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jLabel1)
                            .add(jLabel2)
                            .add(jLabel3))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jComboBoxComuna, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(jComboBoxPartido, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(jTextField_RUT, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
                        .add(18, 18, 18)
                        .add(jButtonEscogerPyC)))
                .addContainerGap(27, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jTextField_RUT, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(jComboBoxPartido, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButtonEscogerPyC))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(jComboBoxComuna, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(11, 11, 11)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jComboBox3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel4)
                    .add(jButton2))
                .add(18, 18, 18)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 64, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(28, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonEscogerPyCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEscogerPyCActionPerformed

        String Resultado;
        String RUT,nombre,comuna = null,partido=null;
        boolean tiene_comuna=false, tiene_partido=false;
        jTextAreaResultado.setText("");
        this.jComboBox3.removeAllItems();
           
        try {
            //Intentamos conectarnos con el servidor
            //Si hay exito empezamos a consumir servicios
            if (conexion.iniciarRegistry(IP_RE)){
                RUT= jTextField_RUT.getText();
                String resultado= conexion.getServidor().dameComuna(RUT);
                
                if(resultado.equals("0")){
                jTextAreaResultado.append("El usuario no tiene comuna registrada"+"\n");
                this.jComboBoxComuna.setSelectedItem("Ninguna");
                }
                else{ 
                tiene_comuna=true;
                jTextAreaResultado.append("Usuario pertenece a la comuna de "+ resultado+"\n");
                comuna=resultado;
                this.jComboBoxComuna.setSelectedItem(resultado);
                }
                
            }//Fin if de conexion
            else{
                JOptionPane.showMessageDialog(this, "No se pudo Conectar a RE", "Mensaje", JOptionPane.ERROR_MESSAGE);
            }
            
        } catch (RemoteException ex) {
            Logger.getLogger(PregRE.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
         try {
             
             if (conexionPP.iniciarRegistry(IP_PP)){
                RUT= jTextField_RUT.getText();
                String resultado= conexionPP.getServidor().damePartido(RUT);
                
                if(resultado.equals("Usuario sin partido")){
                    if(tiene_comuna==true){
                jTextAreaResultado.append("No tiene partido registrado, se usara el partido escogido"+"\n");
                partido= this.jComboBoxPartido.getSelectedItem().toString().trim();
                    }
                    else{
                    }
                }
                else{ 
                tiene_partido=true;
                jTextAreaResultado.append("Usuario pertenece al partido de "+ resultado+"\n");
                partido=resultado;
                this.jComboBoxPartido.setSelectedItem(resultado);
                }
                
            }//Fin if de conexion
            else{
                JOptionPane.showMessageDialog(this, "No se pudo Conectar a PP", "Mensaje", JOptionPane.ERROR_MESSAGE);
            }
             
             } catch (RemoteException ex) {
            Logger.getLogger(PregRE.class.getName()).log(Level.SEVERE, null, ex);
        }
         
         
       if(comuna!=null){
            try {
                String resultado= conexion.getServidor().cargarPrecandidatos(comuna,partido);
                System.out.println(resultado);
                String[] partes=null;
                partes = resultado.split(",");  //Guardo el contenido de linea en un arreglo
                for(int i=0; i<partes.length; i++){
                    
                this.jComboBox3.addItem(partes[i]);
                }
                
            } catch (RemoteException ex) {
                Logger.getLogger(votacionPrimaria.class.getName()).log(Level.SEVERE, null, ex);
            }
       
       }
         
         
         
         
        // TODO add your handling code here:
    }//GEN-LAST:event_jButtonEscogerPyCActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        if(this.jComboBox3.getItemCount()==0){
        this.jTextAreaResultado.setText("Primero ingrese datos correctos de RUT, y partido");
        }
        if(this.jComboBox3.getItemCount()<3 && this.jComboBox3.getItemCount()!=0){
            this.jTextAreaResultado.setText("Lamentablemente faltan precandidatos para poder votar");
        }        
        else{
         
            try {
                String rut= this.jTextField_RUT.getText();
                String candidato= this.jComboBox3.getSelectedItem().toString();
                String partido= this.jComboBoxPartido.getSelectedItem().toString();
                String comuna= this.jComboBoxComuna.getSelectedItem().toString();
                
                String salida=conexion.getServidor().votarPrimario(candidato,rut,comuna,partido);
                this.jTextAreaResultado.setText(salida+"\n");
                
                
            } catch (RemoteException ex) {
                Logger.getLogger(votacionPrimaria.class.getName()).log(Level.SEVERE, null, ex);
            }
       
        
        }
        
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonEscogerPyC;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JComboBox jComboBoxComuna;
    private javax.swing.JComboBox jComboBoxPartido;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea jTextAreaResultado;
    private javax.swing.JTextField jTextField_RUT;
    // End of variables declaration//GEN-END:variables

}
